package com.keste.portal.ui.bean;


import com.keste.portal.ui.util.ADFUtils;
import com.keste.portal.ui.util.JSFUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;

import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.share.ADFContext;
import oracle.adf.share.logging.ADFLogger;
import oracle.adf.view.rich.component.rich.fragment.RichDeclarativeComponent;
import oracle.adf.view.rich.component.rich.input.RichSelectManyShuttle;
import oracle.adf.view.rich.event.DialogEvent;
import oracle.adf.view.rich.event.PopupCanceledEvent;
import oracle.adf.view.rich.event.PopupFetchEvent;

import oracle.binding.BindingContainer;
import oracle.binding.OperationBinding;

import oracle.jbo.Row;
import oracle.jbo.ViewObject;
import oracle.jbo.domain.Number;


public class ProjectManagementBean {

    private RichSelectManyShuttle selectManyShuttleComponent;
    private List selectedEmployees;
    private List allEmployees;
    private Boolean refeshSelectedEmployees = false;
    private static final String CLASSNAME =
        ProjectManagementBean.class.getName();
    private static final ADFLogger LOGGER =
        ADFLogger.createADFLogger(ProjectManagementBean.class);
    private RichDeclarativeComponent taskRemainingTime;
    private RichDeclarativeComponent taskTimeSpent;

    public ProjectManagementBean() {
    }


    public void setSelectedEmployees(List selectedEmployees) {
        this.selectedEmployees = selectedEmployees;
    }

    public List getSelectedEmployees() {
        if (selectedEmployees == null || refeshSelectedEmployees) {
            selectedEmployees = employeeList();
        }
        return selectedEmployees;
    }

    public void setAllEmployees(List allEmployees) {
        this.allEmployees = allEmployees;
    }

    public List getAllEmployees() {
        if (allEmployees == null) {
            allEmployees = selectAllEmployees();
        }
        return allEmployees;
    }

    public void addProjectPopupFetchListner(PopupFetchEvent popupFetchEvent) {
        if (popupFetchEvent.getLaunchSourceClientId().contains("cb3")) {
            OperationBinding operation =
                ADFUtils.findOperation("CreateInsert1");
            operation.execute();
        }
    }

    public void addProjectPopupCanceledListener(PopupCanceledEvent popupCanceledEvent) {
        // Add event code here...
        OperationBinding operation = ADFUtils.findOperation("Rollback");
        operation.execute();
    }

    public void addDialogListner(DialogEvent dialogEvent) {
        if (DialogEvent.Outcome.ok.equals(dialogEvent.getOutcome())) {
            OperationBinding operation = ADFUtils.findOperation("Commit");
            operation.execute();
        } else {
            OperationBinding operation = ADFUtils.findOperation("Rollback");
            operation.execute();
        }
    }

    public void onSearchProject(ActionEvent actionEvent) {
        LOGGER.entering(CLASSNAME, "onSearchProject");
        ViewObject projectDetailsTransientVO =
            ADFUtils.findIterator("ProjectDetailsTransientIterator").getViewObject();
        Row transRow = projectDetailsTransientVO.getCurrentRow();
        if (transRow != null)
            if (transRow.getAttribute("ProjectName") != null ||
                transRow.getAttribute("ProjectStatus") != null) {
                OperationBinding operBind =
                    ADFUtils.findOperation("filterProjects");
                if (transRow.getAttribute("ProjectName") != null) {
                    operBind.getParamsMap().put("Name",
                                                transRow.getAttribute("ProjectName"));
                }
                if (transRow.getAttribute("ProjectStatus") != null) {
                    System.out.println("stgatus" +
                                       transRow.getAttribute("ProjectStatus"));
                    operBind.getParamsMap().put("Status",
                                                transRow.getAttribute("ProjectStatus"));
                }
                operBind.execute();
            } else {
                JSFUtils.addFacesErrorMessage("Please enter any one value");
            }
    }

    public void resetProject(ActionEvent actionEvent) {
        // Add event code here...
        BindingContext context = BindingContext.getCurrent();
        BindingContainer bc = context.getCurrentBindingsEntry();
        OperationBinding emptyOperation =
            bc.getOperationBinding("emptyProjectTable");
        emptyOperation.execute();
        OperationBinding deleteOperation = bc.getOperationBinding("Delete");
        deleteOperation.execute();
        OperationBinding createOperation =
            bc.getOperationBinding("CreateInsert");
        createOperation.execute();
    }

    public void addTaskPopupFetchListner(PopupFetchEvent popupFetchEvent) {
        if (popupFetchEvent.getLaunchSourceClientId().contains("cb1")) {
            OperationBinding operation =
                ADFUtils.findOperation("CreateInsert1");
            operation.execute();
        }
    }

    public void addTaskPopupCanceledListener(PopupCanceledEvent popupCanceledEvent) {
        // Add event code here...
        OperationBinding operation = ADFUtils.findOperation("Rollback");
        operation.execute();
    }

    public void addTaskDialogListner(DialogEvent dialogEvent) {
        if (dialogEvent.getOutcome().name().equals("ok")) {
            OperationBinding operation = ADFUtils.findOperation("Commit");
            operation.execute();
        } else {
            OperationBinding operation = ADFUtils.findOperation("Rollback");
            operation.execute();
        }
    }

    public void onTaskSearch(ActionEvent actionEvent) {
        // Add event code here...
        String taskName = null, taskStatus = null;

        DCIteratorBinding taskTransientIterator =
            ADFUtils.findIterator("TaskTransientIterator");

        if (taskTransientIterator.getCurrentRow().getAttribute("TaskName") !=
            null) {
            taskName =
                    taskTransientIterator.getCurrentRow().getAttribute("TaskName").toString();
        }

        if (taskTransientIterator.getCurrentRow().getAttribute("TaskStatus") !=
            null) {
            taskStatus =
                    taskTransientIterator.getCurrentRow().getAttribute("TaskStatus").toString();
        }

        if ((taskName != null) || (taskStatus != null)) {
            OperationBinding searchTask = ADFUtils.findOperation("searchTask");
            searchTask.getParamsMap().put("taskName", taskName);
            searchTask.getParamsMap().put("taskStatus", taskStatus);
            searchTask.execute();
        } else {
            JSFUtils.addFacesErrorMessage("Plese enter any value.");
        }
    }

    public void resetTask(ActionEvent actionEvent) {
        // Add event code here...
        BindingContext context = BindingContext.getCurrent();
        BindingContainer bc = context.getCurrentBindingsEntry();
        OperationBinding emptyOperation = bc.getOperationBinding("emptyTable");
        emptyOperation.execute();
        OperationBinding deleteOperation = bc.getOperationBinding("Delete");
        deleteOperation.execute();
        OperationBinding createOperation =
            bc.getOperationBinding("CreateInsert");
        createOperation.execute();
    }

    public List employeeList() {
        DCIteratorBinding taskEmployeeMapIterator =
            ADFUtils.findIterator("TaskEmployeeMapIterator");
        List employees = new ArrayList();
        for (Row emp : taskEmployeeMapIterator.getAllRowsInRange()) {
            employees.add(emp.getAttribute("EmployeeId"));
        }
        return employees;
    }

    public List<SelectItem> selectAllEmployees() {
        DCIteratorBinding employeeIterator =
            ADFUtils.findIterator("EmployeeIterator");
        List<SelectItem> selectedEmps = new ArrayList<SelectItem>();
        for (Row emp : employeeIterator.getAllRowsInRange()) {
            SelectItem s = new SelectItem();
            s.setLabel(emp.getAttribute("FirstName").toString() + " " +
                       emp.getAttribute("LastName").toString());
            s.setValue(emp.getAttribute("EmployeeId").toString());
            selectedEmps.add(s);
        }
        return selectedEmps;
    }

    public void refreshSelectedEmployeesList() {
        refeshSelectedEmployees = true;
    }

    public void onShuttleSave(ActionEvent actionEvent) {
        DCIteratorBinding taskEmployeeMapIterator =
            ADFUtils.findIterator("TaskEmployeeMapIterator");

        for (Row emp : taskEmployeeMapIterator.getAllRowsInRange()) {
            emp.remove();
        }

        if (this.getSelectedEmployees().size() > 0) {
            for (int i = 0; i < selectedEmployees.size(); i++) {

                Row row =
                    taskEmployeeMapIterator.getRowSetIterator().createRow();
                Map pageFlowScope = ADFContext.getCurrent().getPageFlowScope();
                Number taskId = (Number)pageFlowScope.get("taskId");
                row.setNewRowState(Row.STATUS_INITIALIZED);
                row.setAttribute("TaskId", taskId);
                row.setAttribute("EmployeeId", getSelectedEmployees().get(i));

                taskEmployeeMapIterator.getRowSetIterator().insertRow(row);
                taskEmployeeMapIterator.setCurrentRowWithKey(row.getKey().toStringFormat(true));
            }
        }

        OperationBinding commit = ADFUtils.findOperation("Commit");
        commit.execute();
    }

    public Double getTimeSpent() {
        Double estimatedTime = ((Number)ADFUtils.evaluateEL("#{bindings.EstimatedTime.inputValue}")).doubleValue();
        Double timeSpent = ((Number)ADFUtils.evaluateEL("#{bindings.TimeSpent.inputValue}")).doubleValue();
        Double res = 0.0;
        if(estimatedTime!=0){
            res=300*timeSpent/estimatedTime;
        }
        return res;
    }

    public Double getRemainingTime() {
        Double estimatedTime = ((Number)ADFUtils.evaluateEL("#{bindings.EstimatedTime.inputValue}")).doubleValue();
        Double timeSpent = ((Number)ADFUtils.evaluateEL("#{bindings.TimeSpent.inputValue}")).doubleValue();
        Double res = 0.0;
        if(estimatedTime!=0){
            res=300-(300*timeSpent/estimatedTime);
        }
        return res;
    }

    public void taskEmployeeMapEditDialogListener(DialogEvent dialogEvent) {
        if (dialogEvent.getOutcome().name().equals("ok")) {
            OperationBinding operation = ADFUtils.findOperation("Commit");
            operation.execute();
        } else {
            OperationBinding operation = ADFUtils.findOperation("Rollback");
            operation.execute();
        }
    }

    public void taskEmployeeMapEditPopupCanceledListener(PopupCanceledEvent popupCanceledEvent) {
        // Add event code here...
        OperationBinding operation = ADFUtils.findOperation("Rollback");
        operation.execute();
    }
}
